package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ClazzMapper clazzMapper;

    @Override
    public PageResult list(String name, Integer degree, Integer clazzId, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        Page<Student> students = (Page<Student>) studentMapper.list(name, degree, clazzId);
        PageResult<Student> pageResult = new PageResult<>();
        pageResult.setTotal(students.getTotal());
        pageResult.setRows(students.getResult());
        return pageResult;
    }

    @Override
    public void add(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
//        插入除班级名称外字段
        studentMapper.add(student);
//根据班级id查询班级名称并赋值给 student 的clazzName
        Integer clazzId = student.getClazzId();
        String name = clazzMapper.findNameById(clazzId);
        student.setClazzName(name);
    }

    @Override
    public Student queryById(Integer id) {
        return studentMapper.queryById(id);
    }

    @Override
    public void update(Student student) {
        studentMapper.update(student);
    }

    @Override
    public void updateViolation(Integer id, Integer score) {
       // Student student = studentMapper.queryById(id);
       // student.setViolationCount((short) (student.getViolationCount() + 1));
       // student.setViolationScore((short) (student.getViolationScore() + score));


//        判断score是否为空
        if (score == null){
            throw new RuntimeException("请输入扣分数");
        }
        studentMapper.updateViolation(id,score);
    }

    @Override
    public void delete(Integer[] ids) {
        studentMapper.delete(ids);
    }
}
